#################################################################################
## 2025-06-04 F 
## 数据检查工具 & 定时任务执行工具 & 数据统计工具
## 根据选项决定是否启用;
## 监听主题,并处理消息
#################################################################################


import paho.mqtt.client as mqtt
import os
import configparser
#from loguru import logger
from top.wardyan.core.utils.mylog import *
from top.wardyan.core.vo.mqtt import MqttMsg
import uuid
from top.wardyan.core.utils.common import *
from top.wardyan.core.erp.erp import *
import time
import zlib
#import pickle
import json
import asyncio
from concurrent.futures import ThreadPoolExecutor
from top.wardyan.core.mqtt import mqttconfig

CACEH_SQLS : dict = {}


def send_query_sql(id : int) :
    global send
    try :
        msg : MqttMsg = MqttMsg(str(uuid.uuid4()), ERP_CUSTCODE, current_timestamp(), "", id, ERP_CUSTCODE, "", 10106, data=id)
        mqttconfig.send( message=msg)
    except Exception as e :
        logger.error(e)



def handle_10106(msg : dict) :
    #print(msg)
    ## msg的内容是:
    ## {'business': 10106, 'custcode': 'XGM', 'data': {'code': 200, 'datas': {...}, 'msg': ''}, 'id': '32c5b4b43ea8408fb17628f1013600f4', 'message': '21000050', 'receiver': 'checktoolclient_XGM', 'sender': 'checktoolserver', 'timestamp': 1749116616424, 'topic': 'checktoolclient_XGM'}
    ## 需要取出deata里的datas, 要判断code是否为200
    if "code" in msg["data"] and msg["data"]["code"] == 200 :
        datas = msg["data"]["datas"]
        sID = datas["sID"]
        if sID > 0 :
            CACEH_SQLS[sID] = datas


def downloadsqls(checks : list) :
    """
    下载SQL. 如何实现定时刷新这个SQL,避免长时间没得更新?
    """
    for check in checks :
        sID = check["sID"]
        xDataType = check["xDataType"]
        # print(f"sID:{sID}, xDataType:{xDataType}")
        if sID is not None and sID > 0 :
            ## 判断本地有没有在内存中缓存, 没有的话向服务器请求查询
            if sID not in CACEH_SQLS.keys() :
                ## 向服务器请求查询
                send_query_sql(sID)
                ## time.sleep(1)
            # else :
            #     print("已在缓存内:", sID)


def execcheck(checkid) -> dict :
    # query()
    if checkid is not None and "sID" in checkid :
        sID = checkid.get("sID")
        data = {}
        data["rCheck_ID"] = -1
        data["xBeginTime"] = current_timestamp()
        data["xEndTime"] = ""
        data["xIsOK"] = True       ## True表示有问题
        data["xErrorCode"] = 0
        data["xLevel"] = 0
        data["xType"] = 0
        data["xNote"] = ""
        data["xCost"] = 0           ## 这个需要我们在客户端计算? 不需要吧
        data["xFieldList"] = ""
        data["rCheck_ID"] = sID
        check = CACEH_SQLS.get(sID)
        # print("****************************************")
        # print(check)
        if check is not None :
            rs = []
            error : bool = False
            try :
                sql = check["xSQL"]
                rs = query(sql)
                if rs is None or len(rs) == 0 :
                    ## 一行结果都没有,表名是OK的
                    data["xIsOK"] = False
                    data["xNote"] = "没有返回结果,默认OK"
                else :
                    ## 只能处理第一行
                    firstrow = rs[0]
                    if "xIsOK" in firstrow :
                        data["xIsOK"] = bool(firstrow["xIsOK"])
                    if "xErrorCode" in firstrow :
                        data["xErrorCode"] = int(firstrow["xErrorCode"])
                    if "xLevel" in firstrow :
                        data["xLevel"] = int(firstrow["xLevel"])
                    if "xType" in firstrow :
                        data["xType"] = int(firstrow["xType"])
                    if "xNote" in firstrow :
                        data["xNote"] = str(firstrow["xNote"])
                    if "xData" in firstrow :
                        data["xData"] = str(firstrow["xData"])
                    if "xFieldList" in firstrow :
                        data["xFieldList"] = str(firstrow["xFieldList"])
            except Exception as e :
                logger.error(e)
                rs = []
                ## 什么结果都没有是不允许的
                data["xIsOK"] = True
                data["xErrorCode"] = 0
                data["xLevel"] = 4      ## 0无 1通知 2预警 3高风险预警 4错误 5严重错误
                data["xType"] = 4       ## 0无需处理 1忽略 2自动处理 3半自动处理 4人工处理
                data["xNote"] = str(e)

        data["xEndTime"] = current_timestamp()
        return data
    else :
        return None

def docheck(checks : list) :
    ## 先检查尝试下载
    downloadsqls(checks)
    ## 执行SQL检查并把内容返回给服务器
    checkmain : dict = {}
    checkmain["xCust"] = ERP_CUSTCODE
    checkmain["xBeginTime"] = current_timestamp()
    items = []
    for check in checks :
        item = execcheck(check)
        if item is not None :
            items.append(item)
    checkmain["items"] = items
    checkmain["xEndTime"] = current_timestamp()
    msg : MqttMsg = MqttMsg(str(uuid.uuid4()), ERP_CUSTCODE, current_timestamp(), "", "", "", "", 13101, data=checkmain)
    mqttconfig.send( message=msg)


def handle_10204(msg : dict) :
    """
    收到通知,更新本地SQL缓存
    """
    pass
